package com.leave.realm;

import java.util.Set;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;

import com.leave.entity.User;
import com.leave.service.IRoleService;
import com.leave.service.IUserService;


public class MyRealm extends AuthorizingRealm {
	@Autowired
	private IRoleService roleService;
	@Autowired
	private IUserService userService;
	
	/**
	 * 角色与权限
	 */
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
		//能进入到这里，表示账号已经通过验证了
		User user =(User) principalCollection.getPrimaryPrincipal();
		//通过service获取角色和权限
		Set<String> roles = roleService.getRoleNameByLoginName(user.getUserLoginname());
		//授权对象
		SimpleAuthorizationInfo s = new SimpleAuthorizationInfo();
		//把通过service获取到的角色和权限放进去
		s.setRoles(roles);
		return s;
	}
	/**
	 * 登录与验证
	 */
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
		//获取账号密码
		UsernamePasswordToken t = (UsernamePasswordToken) token;
		String loginName= token.getPrincipal().toString();
		String password= new String( t.getPassword());
		//获取数据库中的密码
		User u = userService.getUserByLoginName(loginName);

		//如果为空就是账号不存在，如果不相同就是密码错误，但是都抛出AuthenticationException，而不是抛出具体错误原因，免得给破解者提供帮助信息
		if(null==u.getUserPassword() || !u.getUserPassword().equals(password)) 
			throw new AuthenticationException();
		
		//认证信息里存放账号密码, getName() 是当前Realm的继承方法,通常返回当前类名 :MyRealm
		SimpleAuthenticationInfo a = new SimpleAuthenticationInfo(u,u.getUserPassword(),getName());
		return a;
	}

}
